const router = require('koa-router')();
const mysqlHelper = require('../libs/MySQLHelper');
const scripts = require('../configs/scripts/msyql');

router.prefix('/api/requirement');

// 需求查询接口
router.post('/search', async (ctx, next) => {
    await mysqlHelper.queryForList(scripts.RequirementQuery, ctx.request.body,
            builder => builder.and('GUID=@Guid')
            .and('TenantGuid=@TenantGuid', p => p.NeedLogOn)
            .and('Province=@Province')
            .and('City=@City')
            .and('District=@District')
            .and('Venue like concat("%",@Venue, "%")')
            .and('StorageType=@StorageType')
            .and('WareHouseType=@WareHouseType')
            .and('TotalAreaAge>=@MinTotalAreaAge')
            .and('TotalAreaAge<=@MaxTotalAreaAge')
            .and('Platform=@Platform')
            .and('LeasingPrice>=@MinLeasingPrice')
            .and('LeasingPrice<=@MaxLeasingPrice')
            .and('FireFighting=@FireFighting')
            .and('BuildingStructure=@BuildingStructure')
            .and('FloorHeight>=@MinFloorHeight')
            .and('FloorHeight<=@MaxFloorHeight')
            .and('IsPublish=@IsPublish')
            .desc('CREATE_TIME')
            .paging()
        )
        .then(rs => ctx.body = rs, reason => ctx.body = reason);
});

// 需求详情查询接口
router.get('/details/:id', async (ctx, next) => {
    await mysqlHelper.query(scripts.RequirementQuery, {
                id: ctx.params.id
            },
            builder => builder.and('Guid = @id')
        )
        .then(rs => ctx.body = rs.datas[0] || {}, reason => ctx.body = reason);
});

// 需求新增，修改接口
router.post('/save', async (ctx, next) => {
    let data = ctx.request.body;
    let user = ctx.session.user;

    data.TenantGuid = user.TenantGUID;
    data.CreateUserID = user.StaffID;
    data.CreateUserName = user.Name;
    data.UpdateUserID = user.StaffID;
    data.UpdateUserName = user.Name;

    if (!data.GUID) {
        data.GUID = mysqlHelper.generateUUID();

        await mysqlHelper.query(scripts.AddRequirement, data).then(rs => {
            rs.guid = data.GUID;

            ctx.body = rs;
        }, reason => ctx.body = reason);
    } else {
        await mysqlHelper.query(scripts.UpdateRequirement, data).then(rs => ctx.body = rs, reason => ctx.body = reason);
    }
});

// 需求发布接口
router.post('/publish', async (ctx, next) => {
    let values = {
        IsPublish: 'Y',
        Guid: ctx.request.body.GUID
    }

    await mysqlHelper.query(scripts.PublishRequirement, values).then(rs => ctx.body = rs, reason => ctx.body = reason);
});

// 需求删除接口
router.post('/delete', async (ctx, next) => {
    await mysqlHelper.query(scripts.RemoveRequirement, ctx.request.body).then(rs => ctx.body = rs, reason => ctx.body = reason);
});

module.exports = app => {
    app.use(router.routes(), router.allowedMethods());

    return router;
};